<template>
  <div>
    <h1>订单列表</h1>
    <!-- 条件搜索 -->
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="订单名称">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入订单名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchForm.statusId"
            placeholder="请选择订单状态"
            clearable
          >
            <el-option label="未支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="待发货" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select
            v-model="searchForm.typeId"
            placeholder="请选择订单类型"
            clearable
          >
            <el-option
              v-for="item in orderTypeList"
              :label="item.dictName"
              :value="item.dictValue"
              :key="item.dictId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadOrderList">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin-top: 10px">
      <el-button type="primary" @click="onAddOrder">添加订单</el-button>
      <el-button type="danger" @click="onDeleteBatchOrder">批量删除</el-button>
      <el-button type="primary" @click="onExportOrder">导出</el-button>
    </div>
    <!-- 表格数据 -->
    <div style="margin-top: 10px">
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column prop="orderId" label="ID" width="60" />
        <el-table-column prop="orderNo" label="订单编号" width="120" />
        <el-table-column prop="prodInfo" label="商品信息" width="140" />
        <el-table-column prop="orderAmount" label="订单金额" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="120" />
        <el-table-column prop="createBy" label="消费者" width="100" />
        <el-table-column prop="imageList" label="商品图片" width="160">
          <template #default="scope">
            <el-image
              v-for="item in scope.row.imageList"
              :src="item"
              :key="item.id"
              style="width: 50px; height: 50px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.orderStatus == 0">未支付</el-tag>
            <el-tag v-if="scope.row.orderStatus == 1">已支付</el-tag>
            <el-tag v-if="scope.row.orderStatus == 2">待发货</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              @click="handleViewOrder(scope.row)"
              size="smlall"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 10px">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加订单---对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" :title="title" width="700">
        <el-form :model="form">
          <el-form-item label="选择商品" :label-width="formLabelWidth">
            <el-select v-model="form.infoId" placeholder="请选择商品" >
              <el-option
                v-for="item in prodInfoList"
                :label="item.prodName"
                :value="item.infoId"
                :key="item.infoId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="购买数量" :label-width="formLabelWidth">
            <el-input v-model="form.buyNum" autocomplete="off" />
          </el-form-item>
          <div style="margin-top: 10px">
            <el-button type="primary" @click="addProdInfo">添加</el-button>
          </div>
          <div style="margin-top: 10px">
            <el-table :data="buyInfoList">
              <el-table-column prop="prodId" label="商品ID" width="100" />
              <el-table-column prop="prodName" label="商品名称" width="150" />
              <el-table-column prop="prodPrice" label="商品价格" width="150" />
              <el-table-column prop="buyNum" label="购买数量" width="150" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button
                    type="danger"
                    @click="ondeletebuyInfo(scope.row)"
                    size="small"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div>总结：{{ totalAmount }} 元</div>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="onSumbitAddOrder">
              提交订单
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getOrderList,
  getProdInfoList,
  addOrder,
  getDietList,
  deleteBatchOrder,
} from "../api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

const tableData = ref([]);
const total = ref(0);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
  typeId: null,
  statusId: null,
});

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = ref({
  infoId: null,
  buyNum: 1,
});

const title = ref("添加订单");

const prodInfoList = ref([]);
const buyInfoList = ref([]);
const totalAmount = ref(0);

//导出
const onExportOrder = () => {
  window.open(
    "http://localhost:9011/shop/order/exportOrderList/" + user.value.userId
  );
};

//批量删除
const onDeleteBatchOrder = () => {
  if (multipleSelection.value == null || multipleSelection.value.length == 0) {
    ElMessage.warning("请先选择你要删除的数据");
    return;
  }

  let ids: any = [];
  multipleSelection.value.forEach((item) => {
    ids.push(item.orderId);
  });

  ElMessageBox.confirm("数据删除后无法恢复，你确定要删除所选数据吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteBatchOrder(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          loadOrderList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//多选
const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

//查看订单详情
const handleViewOrder = (row: any) => {
  console.log("handleViewOrder", row);
  sessionStorage.setItem("orderId",row.orderId)
  router.push("/home/orderinfo")
};

//提交添加订单
const onSumbitAddOrder = () => {
  console.log("onSumbitAddOrder");
  addOrder(buyInfoList.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      loadOrderList();
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//删除购物车数据
const ondeletebuyInfo = (row: any) => {
  buyInfoList.value.forEach((item, index) => {
    if (item.infoId === row.infoId) {
      buyInfoList.value.splice(index, 1);
    }
  });

  //动态计算订单总价
  totalAmount.value = 0.0;
  buyInfoList.value.forEach((item) => {
    totalAmount.value += item.prodPrice * item.buyNum;
  });
};

//添加商品到购物车
const addProdInfo = () => {
  console.log("addProdInfo");
  prodInfoList.value.forEach((item) => {
    if (item.infoId === form.value.infoId) {
      item.buyNum = form.value.buyNum;

      buyInfoList.value.push(item);
    }
  });
  //动态计算订单总价
  totalAmount.value = 0.0;
  buyInfoList.value.forEach((item) => {
    totalAmount.value += item.prodPrice * item.buyNum;
  });
};

//显示添加订单对话框
const onAddOrder = () => {
  console.log("onAddOrder");
  title.value = "添加订单";
  form.value = {
    infoId: null,
    buyNum: 1,
  };
  buyInfoList.value = [];
  totalAmount.value = 0.0;
  dialogFormVisible.value = true;
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadOrderList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadOrderList();
};

const loadOrderList = () => {
  getOrderList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

const orderTypeList = ref([]);
const user = ref({
  userId: null,
});
onMounted(() => {
  loadOrderList();
  getProdInfoList().then((res) => {
    if (res.data.code == 200) {
      prodInfoList.value = res.data.data;
    }
  });

  getDietList(4).then((res) => {
    if (res.data.code == 200) {
      orderTypeList.value = res.data.data;
    }
  });

  let u = sessionStorage.getItem("user");
  let use = JSON.parse(u);
  user.value = use;
});
</script>

<!-- 条件搜索样式 -->
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
<!-- 分页样式 -->
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
